namespace :tressaweb do
  desc 'Sends notifications to both company and client about the recently created order.'
  task :send_order_emails => :environment do
    order_notifications = OrderNotification.all

    puts 'Getting notifications...'

    order_notifications.each do |notification|
      begin
        puts "Processing notification #{notification.id}"
        order = Order.find(notification.order_id)
        # Notification for the company
        UserMailer.order_alert(order).deliver

        # Notification for the client
        UserMailer.order_received(order).deliver

        # Removes the notification once sent.
        OrderNotification.destroy(notification.id)
      rescue Exception => ex
        puts "Notification #{notification.id} couldn't been processed"
        puts "Error: " + ex.message
      end
    end
  end

  desc 'Deletes expired pending orders'
  task :delete_expired_saved_items => :environment do
    ttl_days = configatron.order_ttl_days
    thold_date = eval('ttl_days.days.ago').to_date

    items_to_delete = SavedCart.where("DATE(created_at) < ?", thold_date)

    unless items_to_delete.blank?
      items_to_delete.delete_all
    end
  end
end